<template>
  <div>
  	<div class="consume-box">
	    <p class="title">添加商品目录</p>
	    <Form ref="addGoodsNameForm" :model="addGoodsNameData" :rules="addGoodsNameRule" :label-width="120">
	        <Row :gutter="16">
	            <Col span="12">
	                <FormItem label="商品一级类目:">
	                    <Select placeholder="请选择商品一级类目" style="width:100%" @on-change="getGoodsTwo">
	                        <Option v-for="item in goodsOne" :value="item.id" :key="item.id">{{ item.name }}</Option>
	                    </Select>
	                </FormItem>
	            </Col>
	            <Col span="12">
	                <FormItem label="商品二级类目:" prop="productCategory">
	                    <Select v-model="addGoodsNameData.productCategory" placeholder="请选择商品二级类目" :loading="isGetGoodsTwo" style="width:100%">
	                        <Option disabled v-if="goodsTwo.length == 0" value="">请先商品一级类目</Option>
	                        <Option v-for="item in goodsTwo" :value="item.id" :key="item.id">{{ item.name }}</Option>
	                    </Select>
	                </FormItem>
	            </Col>
	            <Col span="12">
	                <FormItem label="商品名称:" prop="name">
	                    <Input v-model="addGoodsNameData.name" placeholder="请输入商品名称"></Input>
	                </FormItem>
	            </Col>
	            <Col span="12">
	                <FormItem label="商品编号:" prop="number">
	                    <Input v-model="addGoodsNameData.number" placeholder="请输入商品编号"></Input>
	                </FormItem>
	            </Col>
	            <Col span="12">
	                <FormItem label="商品进价:" prop="purchasePrice">
	                    <Input v-model="addGoodsNameData.purchasePrice" placeholder="请输入商品进价"></Input>
	                </FormItem>
	            </Col>
	            <Col span="12">
	                <FormItem label="商品售价:" prop="originalPrice">
	                    <Input v-model="addGoodsNameData.originalPrice" placeholder="请输入商品售价"></Input>
	                </FormItem>
	            </Col>
	        </Row>
	        <FormItem label="参与积分兑换:" prop="isScore">
	            <RadioGroup v-model="addGoodsNameData.isScore" @on-change="changeIsCanScore">
	                <Radio label="1">是</Radio>
	                <Radio label="99">否</Radio>
	            </RadioGroup>
	        </FormItem>
	        <FormItem label="兑换所需积分:" prop="score">
	            <Input :disabled="isCanScore" type="text" v-model="addGoodsNameData.score" placeholder="请输入兑换所需积分"></Input>
	        </FormItem>
	        <FormItem label="参与会员优惠:" prop="isVip">
	            <RadioGroup v-model="addGoodsNameData.isVip" @on-change="changeIsCanVip">
	                <Radio label="1">是</Radio>
	                <Radio label="99">否</Radio>
	            </RadioGroup>
	        </FormItem>
	        <FormItem label="金卡折扣:" prop="goldDiscount">
	            <Input :disabled="isCanVip" type="text" v-model="addGoodsNameData.goldDiscount" placeholder="请输入金卡折扣"></Input>
	        </FormItem>
	        <FormItem label="银卡折扣:" prop="silverDiscount">
	            <Input :disabled="isCanVip" type="text" v-model="addGoodsNameData.silverDiscount" placeholder="请输入银卡折扣"></Input>
	        </FormItem>
	        <FormItem label="普卡折扣:" prop="commonDiscount">
	            <Input :disabled="isCanVip" type="text" v-model="addGoodsNameData.commonDiscount" placeholder="请输入普卡折扣"></Input>
	        </FormItem>
	
	        <div class="buttonbox">
	            <Button type="ghost" @click="resetGoodsName('addGoodsNameForm')">重置</Button>
	            <Button :loading="isKeep" type="primary" @click="addGoodsName('addGoodsNameForm')">提交</Button>
	        </div>
	    </Form>
	  </div>
  	<div class="fwb">
  			<div class="img-box1">
  				<h3 class="h3">上传图片一</h3>
  					<div class="img1">
	  				<img class="shopimg" :src="pic.pic1" v-if="pic.pic1!==''"/>
		  			<div class="oDiv">
		  				<Upload :show-upload-list="false" :before-upload="handleBeforeUpload" :on-success="handleSuccess" action="http://192.168.6.87:9090/upload/image" :data="images">
			  				<div style="width: 80px;height:80px;line-height: 80px;">
			            <Icon type="ios-camera" size="20"></Icon>
			        </div>
							</Upload>
		  			</div>
	  			</div>
  			</div>
  			
				<div class="img-box1">
  				<h3 class="h3">上传图片二</h3>
  					<div class="img1">
	  				<img class="shopimg" :src="pic.pic2" v-if="pic.pic2!==''"/>
		  			<div class="oDiv">
		  				<Upload :show-upload-list="false" :before-upload="handleBeforeUpload2" :on-success="handleSuccess2" action="http://192.168.6.87:9090/upload/image" :data="images">
			  				<div style="width: 80px;height:80px;line-height: 80px;">
			            <Icon type="ios-camera" size="20"></Icon>
			        </div>
							</Upload>
		  			</div>
	  			</div>
  			</div>
  			<div class="img-box1">
  				<h3 class="h3">上传图片三</h3>
  					<div class="img1">
	  				<img class="shopimg" :src="pic.pic3" v-if="pic.pic3!==''"/>
		  			<div class="oDiv">
		  				<Upload :show-upload-list="false" :before-upload="handleBeforeUpload3" :on-success="handleSuccess3" action="http://192.168.6.87:9090/upload/image" :data="images">
			  				<div style="width: 80px;height:80px;line-height: 80px;">
			            <Icon type="ios-camera" size="20"></Icon>
			        </div>
							</Upload>
		  			</div>
	  			</div>
  			</div>
  			<div class="img-box1">
  				<h3 class="h3">上传图片四</h3>
  					<div class="img1">
	  				<img class="shopimg" :src="pic.pic4" v-if="pic.pic4!==''"/>
		  			<div class="oDiv">
		  				<Upload :show-upload-list="false" :before-upload="handleBeforeUpload4" :on-success="handleSuccess4" action="http://192.168.6.87:9090/upload/image" :data="images">
			  				<div style="width: 80px;height:80px;line-height: 80px;">
			            <Icon type="ios-camera" size="20"></Icon>
			        </div>
							</Upload>
		  			</div>
	  			</div>
  			</div>
  			<div class="img-box1">
  				<h3 class="h3">上传图片五</h3>
  					<div class="img1">
	  				<img class="shopimg" :src="pic.pic5" v-if="pic.pic5!==''"/>
		  			<div class="oDiv">
		  				<Upload :show-upload-list="false" :before-upload="handleBeforeUpload5" :on-success="handleSuccess5" action="http://192.168.6.87:9090/upload/image" :data="images">
			  				<div style="width: 80px;height:80px;line-height: 80px;">
			            <Icon type="ios-camera" size="20"></Icon>
			        </div>
							</Upload>
		  			</div>
	  			</div>
  			</div>
  			
  			<Form class="form" :label-width="70">
  				<FormItem label='产品信息:' v-for="item in product">
						<Input v-model="item.pInfo" placeholder="例如:品牌" style="width: 130px; margin: 0 3px;"></Input>
						<Input v-model="item.pInfo2" placeholder="例如:德生" style="width: 130px; margin: 0 3px;"></Input>
					</FormItem>
					<Icon type="plus-round" color="#0b9595" @click="addInput" class="addicon"></Icon>
					<div style="position: relative;">
						<FormItem label='产品规格:' v-for="item in pSpecData">
							<Input v-model="item.pSpec" placeholder="例如:规格" style="width: 130px; margin: 0 3px;"></Input>
							<Input v-model="item.pSpec2" placeholder="例如:黄色" style="width: 130px; margin: 0 3px;"></Input>
						</FormItem>
						<Icon type="plus-round" color="#0b9595" style='position: absolute;right: -20px;top: 10px;' @click="addpSpec"></Icon>
					</div>
  			</Form>
  	</div>
  	<editor id="editor_id" height="400px" width="600px" v-model='addGoodsNameData.pDetail' :content="addGoodsNameData.pDetail" :loadStyleMode="false" @on-content-change="onContentChange">{{addGoodsNameData.pDetail}}</editor>
  	
  </div>
	
</template>
<script>
	import uploadPic from "@/components/common/UploadPic.vue";
export default {
	components: {
			uploadPic
		},
  data() {
    //   验证折扣
    const discountRule = (rule, value, callback) => {
      //   支持手机号码，3-4位区号，7-8位直播号码
      let discountReg = /((^[0|1]$)|(^0\.\d{1,2}$))/;
      if (value === "") {
        callback(new Error("请输入对应折扣"));
      } else if (!discountReg.test(value)) {
        callback(new Error("请输入正确的0到1的数字,且最多保留两位小数位"));
      } else {
        callback();
      }
    };
    return {
    	count: 0,
    	pSpecCount: 0,
    	pic: {
    		pic1: '',
    		pic2: '',
    		pic3: '',
    		pic4: '',
    		pic5: ''
    	},
    	images: {
    		type: 4,
				image: null
    	},
    	newsData: {
    		content: ''
    	},
      goodsOne: [],
      goodsTwo: [],
      isGetGoodsTwo: false,
      isCanScore: true,
      isCanVip: true,
      addGoodsNameData: {
        productCategory: "",
        name: "",
        number: "",
        purchasePrice: "",
        originalPrice: "",
        isScore: "99",
        score: "0",
        isVip: "99",
        goldDiscount: "1",
        silverDiscount: "1",
        commonDiscount: "1",
        picUrl: '',
    		picUrl2: '',
    		picUrl3: '',
    		picUrl4: '',
    		picUrl5: '',
    		pInfo: '',  //商品信息
    		pSpec: '',  //商品规格
    		pDetail: ''  //商品详情
      },
     	product:[{pInfo:'',pInfo2:'',count: 0}],
			pSpecData:[{pSpec:'',pSpec2:'',count: 0}],
      addGoodsNameRule: {
        productCategory: [{ required: true, message: "请选择商品二级类目" }],
        name: [{ required: true, message: "请输入商品名称" }],
        number: [{ required: true, message: "请输入商品编号" }],
        purchasePrice: [{ required: true, message: "请输入商品进价" }],
        originalPrice: [{ required: true, message: "请输入商品售价" }],
        isScore: [{ required: true, message: "请选择是否参与积分兑换" }],
        score: [{ required: true, message: "请输入兑换所需积分" }],
        isVip: [{ required: true, message: "请选择参与会员优惠" }],
        goldDiscount: [{ required: true, validator: discountRule }],
        silverDiscount: [{ required: true, validator: discountRule }],
        commonDiscount: [{ required: true, validator: discountRule }]
      },
      isKeep: false
    };
  },
  created() {
    this.getGoodsOneData();
  },
  methods: {
  	// 处理数据的方法
  	handleMock(){
  		//   {"品牌":"德生,"品牌1":"德1}  后台需要这种数据
  		//  产品信息
			var arr = []
			this.product.forEach((item,index)=>{
				if(index==item.count){
					arr.push(`"${item.pInfo}":"${item.pInfo2}"`)
				}
			})
			let newArr = '{' + arr + '}';
			this.addGoodsNameData.pInfo = newArr;
			console.log(this.addGoodsNameData.pInfo)
			
			// 产品规格
			var pSpecArr = []
			this.pSpecData.forEach((item,index)=>{
				if(index == item.count){
					pSpecArr.push(`"${item.pSpec}":"${item.pSpec2}"`)
				}
			})
			let newpSpec = '{' + pSpecArr + '}';
			this.addGoodsNameData.pSpec = newpSpec;
			console.log(this.addGoodsNameData.pSpec)
  	},
  	//  添加产品规格input
  	addpSpec(){
  		this.pSpecCount++
  		this.pSpecData.push({pSpec:'',pSpec2:'',count: this.pSpecCount})
  	},
  	// 添加产品信息 input 点击加一个input
  	addInput(){
  		this.count++
  		this.product.push({pInfo:'',pInfo2:'',count: this.count})
  	},
  	// 上传图片一
  	handleBeforeUpload(file){
  		this.images.image = file
  	},
  	handleSuccess(file){
  		this.pic.pic1 = 'http://192.168.6.87:9090' + file.data.path;
  		this.addGoodsNameData.picUrl = 'http://192.168.6.87:9090' + file.data.path
  	},
  	// 上传图片二
  	handleBeforeUpload2(file){
  		this.images.image = file
  	},
  	handleSuccess2(file){
  		this.pic.pic2 = 'http://192.168.6.87:9090' + file.data.path;
  		this.addGoodsNameData.picUrl2 = 'http://192.168.6.87:9090' + file.data.path
  	},
  	// 上传图片三
  	handleBeforeUpload3(file){
  		this.images.image = file
  	},
  	handleSuccess3(file){
  		this.pic.pic3 = 'http://192.168.6.87:9090' + file.data.path;
  		this.addGoodsNameData.picUrl3 = 'http://192.168.6.87:9090' + file.data.path
  	},
  	// 上传图片四
  	handleBeforeUpload4(file){
  		this.images.image = file
  	},
  	handleSuccess4(file){
  		this.pic.pic4 = 'http://192.168.6.87:9090' + file.data.path;
  		this.addGoodsNameData.picUrl4 = 'http://192.168.6.87:9090' + file.data.path
  	},
  	// 上传图片五
  	handleBeforeUpload5(file){
  		this.images.image = file
  	},
  	handleSuccess5(file){
  		this.pic.pic5 = 'http://192.168.6.87:9090' + file.data.path;
  		this.addGoodsNameData.picUrl5 = 'http://192.168.6.87:9090' + file.data.path
  	},
  	onContentChange(val) {
//		console.log(val)
			this.addGoodsNameData.pDetail = val;
			console.log(this.addGoodsNameData.pDetail)
		},
    //   获取一级类目
    getGoodsOneData() {
      this.$http
        .post("/product_category_one_list")
        .then(res => {
          // console.log(res);
          this.goodsOne = res.data.productCategoryOne.map(function(e) {
            return {
              id: e.id,
              name: e.name
            };
          });
        })
        .catch(err => {
          console.log(err);
          this.$Notice.error({ title: "商品一级类目获取失败！" });
        });
    },
    //   根据一级目录查询二级目录
    getGoodsTwo(goodsOneId) {
      this.isGetGoodsTwo = true;
      this.$http
        .post("/get_product_category_two", { productCategoyOneId: goodsOneId })
        .then(res => {
          //   console.log(res);
          this.isGetGoodsTwo = false;
          this.goodsTwo = res.data.productCategoryList.map(function(e) {
            return {
              id: e.id,
              name: e.name
            };
          });
        })
        .catch(err => {
          console.log(err);
          this.isGetGoodsTwo = false;
          this.$Notice.error({ title: "商品一级类目获取失败！" });
        });
    },

    // 是否参与积分兑换
    changeIsCanScore(value) {
      if (value === "1") {
        this.isCanScore = false;
      } else {
        this.isCanScore = true;
        this.addGoodsNameData.score = 0;
      }
    },
    // 是否参与会员优惠
    changeIsCanVip(value) {
      if (value === "1") {
        this.isCanVip = false;
      } else {
        this.isCanVip = true;
        this.addGoodsNameData.goldDiscount = 1;
        this.addGoodsNameData.silverDiscount = 1;
        this.addGoodsNameData.commonDiscount = 1;
      }
    },
    // 重置表单
    resetGoodsName(refName) {
      this.$refs[refName].resetFields();
    },
    // 添加商品名录
    addGoodsName(refName) {
    	this.handleMock()  // 调用处理数据方法
      this.$refs[refName].validate(valid => {
        if (valid) {
          this.isKeep = true;
          console.log(this.addGoodsNameData);
          this.$http
            .post("/add_product", this.addGoodsNameData)
            .then(res => {
              // console.log(res);
              this.isCanScore = true;
              this.isCanVip = true;
              this.isKeep = false;
              this.$refs[refName].resetFields();
              this.$Message.success("新增商品名录成功！");
            })
            .catch(err => {
              this.isKeep = false;
              console.log(err);
              this.$Notice.error({ title: "新增商品名录失败！" });
            });
        }
      });
    }
  }
};
</script>
<style lang="less" scoped>


.fwb{
	float: left;
	margin-top: 24px;
	border-right: 1px solid #ccc;
	width: 500px;
	padding: 30px;
	border-radius: 5px;
	.img-box1 {
		float: left;
		margin: 0 auto;
		margin-right: 40px;
		margin-bottom: 20px;
	.h3 {
		color: #0b9595;
	}
	.img1 {
		display: flex;
	}
	.shopimg {
		width: 80px; 
		height: 80px; 
		display: block; 
		margin-right: 10px;
	}
	.oDiv {
		border: 1px dashed #ccc; 
		text-align: center;
		height: 80px;
		width: 80px;
		line-height: 80px; 
		cursor:pointer;
		margin-bottom: 10px;
	}
	.keepPic {
		margin-left: 10px;
		
	}
}
.form {
	float: left;
	position: 
	relative;
	.addicon{
	position: absolute;
	right: -20px;
	top: 10px ;
	}
}
}




.consume-box {
  width: 650px;
  margin: 24px auto 0;
  border-right: 1px solid #ccc;
  border-radius: 5px;
  padding: 30px;
  padding-left: 0;
  float: left;
	margin-right: 40px;
  .title {
    font-size: 16px;
    margin-bottom: 24px;
    color: #0b9595;
    text-align: center;
  }

  .buttonbox {
    text-align: center;

    button {
      margin: 0 4px;
    }
  }
}

</style>
